package com.github.ginirohikocha.dbm.fragment;

import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.github.ginirohikocha.dbm.Address;
import com.github.ginirohikocha.dbm.R;
import com.github.ginirohikocha.dbm.adapter.RecycleOrderAdapter;
import com.github.ginirohikocha.dbm.entity.Order;
import com.github.ginirohikocha.dbm.util.HttpUtil;
import com.zyao89.view.zloading.ZLoadingDialog;
import com.zyao89.view.zloading.Z_TYPE;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.RequestBody;
import okhttp3.Response;

public class OrderWindowFragment extends Fragment {

    private int type;

    private Activity activity;

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        activity = (Activity) context;
    }

    private List<Order> list = new ArrayList<>();

    private SwipeRefreshLayout refresh;
    private RecyclerView orderWindow;
    private RecycleOrderAdapter orderAdatper;

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {

        final View order = inflater.inflate(R.layout.fragment_order_window, container, false);
        //组件绑定
        refresh = order.findViewById(R.id.refresh);//刷新布局
        orderWindow = order.findViewById(R.id.order_window);//订单列表布局
        dialog = new ZLoadingDialog(activity);//加载动画
        dialog.setLoadingBuilder(Z_TYPE.DOUBLE_CIRCLE)//设置类型
                .setLoadingColor(Color.BLACK)//颜色
                .setCanceledOnTouchOutside(false)
                .setCancelable(false)
                .setHintText("加载中...");
        //订单列表布局初始化
        getOrderData();
        //监听绑定
        refresh.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                refresh();
                refresh.setRefreshing(false);
                Toast.makeText(activity, "刷新成功", Toast.LENGTH_SHORT).show();
            }
        });

        return order;
    }

    public static OrderWindowFragment newInstance(int type) {

        Bundle args = new Bundle();
        
        OrderWindowFragment fragment = new OrderWindowFragment();
        fragment.setArguments(args);
        fragment.type = type;

        return fragment;
    }

    public void refresh() {
        getOrderData();
        initRecycleAdapter();
    }

    /**
     * 根据类型获取订单数据
     * **/
    private void getOrderData() {
        JSONObject request = new JSONObject();
        request.put("current", 1);
        request.put("size", 50);
        SharedPreferences workerInfo = activity.getSharedPreferences("worker", 0);
        int id = workerInfo.getInt("id", -1);
        if (id == -1)
            return;
        //处理请求类型
        switch (type) {
            case OrderFragment.WAITING_ORDERS:
                request.put("status", getResources().getString(R.string.pending_orders));
                request.put("workerid", id);
                break;
            case OrderFragment.ACCEPTED_ORDERS:
                request.put("status", getResources().getString(R.string.accepted_orders));
                request.put("workerid", id);
                break;
            case OrderFragment.HANDED_OVER_ORDERS:
                request.put("status", getResources().getString(R.string.handed_over_orders));
                request.put("workerid", id);
                break;
        }
        RequestBody requestBody = RequestBody.create(MediaType.parse("text/plain; charset=utf-8"), request.toString());
        setLoading(true);
        //发出请求
        HttpUtil.sendOkHttpPostRequest(Address.ORDER_QUERY_BRIEF, requestBody, new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Log.w("订单获取", "网络连接错误");
                activity.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        setLoading(false);
                        Toast.makeText(activity, "网络连接错误，请稍后重试", Toast.LENGTH_SHORT).show();
                    }
                });
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String responseBody = response.body().string();
                //Log.d("订单获取", responseBody);
                JSONObject jsonObject = JSONObject.parseObject(responseBody);
                JSONObject page = jsonObject.getJSONObject("page");
                if (page == null)
                    return;
                final JSONArray orders = page.getJSONArray("records");
                list = orders.toJavaList(Order.class);
                activity.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        initRecycleAdapter();
                        setLoading(false);
                    }
                });
            }
        });
    }
    /**
     * 初始化列表界面
     * **/
    private void initRecycleAdapter() {
        if (orderAdatper == null) {
            LinearLayoutManager layoutManager = new LinearLayoutManager(activity);
            layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
            orderWindow.setLayoutManager(layoutManager);
        }
        orderAdatper = new RecycleOrderAdapter(activity, list);
        orderWindow.setAdapter(orderAdatper);
    }

    private ZLoadingDialog dialog;

    /**
     * 设置加载动画开启与否
     * **/
    private void setLoading(boolean b) {
        if (b) {
            dialog.show();
        } else {
            dialog.dismiss();
        }
    }
}
